package com.yonyou.brigade.rtpnr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBaseDocService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.rtpnr.core.CXFInvokeClient;
import com.yonyou.brigade.rtpnr.core.SupportedFunCode;
import com.yonyou.brigade.rtpnr.model.*;
import com.yonyou.brigade.rtpnr.service.IEntInfoService;
import com.yonyou.brigade.rtpnr.service.IRtpnrPublicService;
import com.yonyou.brigade.rtpnr.service.IRtpnrUserService;
import com.yonyou.brigade.rtpnr.util.XMLBeanUtil;
import com.yonyou.brigade.rtpnr.util.XMLStringUtil;
import com.yonyou.ybzboot.starter.common.exception.BaseException;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.bind.JAXBException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
public class RtpnrPublicServiceImpl implements IRtpnrPublicService {
    private static Logger logger = LoggerFactory.getLogger(RtpnrPublicServiceImpl.class);

    @Autowired
    CXFInvokeClient cxfInvokeClient;

    @Autowired
    SupportedFunCode supportedFunCode;

    @Autowired
    @Qualifier("entInfoServiceImpl")
    IEntInfoService entInfoService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;

    @Autowired
    @Qualifier(value = "rtpnrUserServiceImpl")
    private IRtpnrUserService rtpnrUserService;

    @Autowired
    private IBaseDocService baseDocService;


    /**
     * 创建员工
     *
     * @return
     */
    @Override
    public JSONObject createAccountInfo(String tenant, String orgpk, RtpnrUser rtpnrUser) {
        JSONObject jsonObject = new JSONObject();
        /*try {*/
            /*Document document = XMLUtil.newDocument();
            Element e_createAccountInfo_1_0 = document.createElement("CreateAccountInfo_1_0");
            Element e_userName = document.createElement("UserName");
            Element e_mobile = document.createElement("Mobile");
            Element e_isActivation=document.createElement("IsActivation");
            Element e_email= document.createElement("Email");
            Element e_cardName = document.createElement("CardName");
            Element e_cardNo=document.createElement("CardNo");
            Element e_department = document.createElement("Department");

            e_userName.setTextContent(rtpnrUser.getUserName());
            e_mobile.setTextContent(rtpnrUser.getMobile());
            e_isActivation.setTextContent(rtpnrUser.getIsActivation());
            e_email.setTextContent(rtpnrUser.getEmail());
            e_cardName.setTextContent(rtpnrUser.getCardName());
            e_cardNo.setTextContent(rtpnrUser.getCardNo());
            e_department.setTextContent(rtpnrUser.getDepartment());
            e_createAccountInfo_1_0.appendChild(e_userName);
            e_createAccountInfo_1_0.appendChild(e_mobile);
            e_createAccountInfo_1_0.appendChild(e_isActivation);
            e_createAccountInfo_1_0.appendChild(e_email);
            e_createAccountInfo_1_0.appendChild(e_cardName);
            e_createAccountInfo_1_0.appendChild(e_cardNo);
            e_createAccountInfo_1_0.appendChild(e_department);
            document.appendChild(e_createAccountInfo_1_0);
*/
        StringBuffer requestStr = new StringBuffer();
        requestStr.append("<CreateAccountInfo_1_0>");
        requestStr.append("<UserName>" + rtpnrUser.getUserName() + "</UserName>");
        requestStr.append("<Mobile>" + rtpnrUser.getMobile() + "</Mobile>");
        requestStr.append("<IsActivation>" + rtpnrUser.getIsActivation() + "</IsActivation>");
        if (rtpnrUser.getEmail() != null) {
            requestStr.append("<Email>" + rtpnrUser.getEmail() + "</Email>");
        }
        if (rtpnrUser.getCardName() != null) {
            requestStr.append("<CardName>" + rtpnrUser.getCardName() + "</CardName>");
        }
        if (rtpnrUser.getCardNo() != null) {
            requestStr.append("<CardNo>" + rtpnrUser.getCardNo() + "</CardNo>");
        }
        if (rtpnrUser.getDepartment() != null) {
            requestStr.append("<Department>" + rtpnrUser.getDepartment() + "</Department>");
        }
        if (rtpnrUser.getAdmin() == 1) {
            requestStr.append("<UserRole>A</UserRole>");
        } else {
            requestStr.append("<UserRole>B</UserRole>");
        }
        if (!StringUtils.isEmpty(rtpnrUser.getCategory())) {
            requestStr.append("<TravelRule>");
            requestStr.append(rtpnrUser.getCategory());
            requestStr.append("</TravelRule>");
        }
        requestStr.append("<StaffNum>" + rtpnrUser.getStaffNum() + "</StaffNum>");
        requestStr.append("</CreateAccountInfo_1_0>");

        String requestXmlString = requestStr.toString();//XMLStringUtil.doc2String(document);
        logger.info("请求XML字符串->");
        logger.info(requestXmlString);

        String resultXmlString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
        logger.info("返回XML字符串->");
        logger.info(resultXmlString);
        Document resultDocument = XMLStringUtil.string2Doc(resultXmlString);
        Element n_CreateAccountInfo_1_0 = (Element) resultDocument
                .getElementsByTagName("CreateAccountInfo_1_0").item(0);
        if (n_CreateAccountInfo_1_0 != null) {
            NodeList nodeList = n_CreateAccountInfo_1_0.getChildNodes();
            if (nodeList != null && nodeList.getLength() > 0) {
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node node = nodeList.item(i);
                    String nodeName = node.getNodeName();
                    String nodeValue = node.getTextContent();
                    jsonObject.put(nodeName, nodeValue);
                }
            }
        }

        /*} catch (ParserConfigurationException e) {
            throw new BaseException(-100,e.getMessage());
        }*/

        return jsonObject;
    }

    /**
     * 修改员工信息
     *
     * @param tenant
     * @param orgpk
     * @param updateAccountInfo
     * @return
     */
    @Override
    public JSONObject updateAccountInfo(String tenant, String orgpk, UpdateAccountInfo updateAccountInfo) {
        String requestXmlString = "";
        JSONObject jsonObject = new JSONObject();
        EntInfo entInfo = entInfoService.getEntInfoByTenantOrg(tenant, orgpk);
        try {
            requestXmlString = XMLBeanUtil.java2Xml(updateAccountInfo, "UTF-8");
            logger.info("请求XML字符串->");
            logger.info(requestXmlString);
            String resultXmlString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
            logger.info("返回XML字符串->");
            logger.info(resultXmlString);

//            UpdateAccountInfoReturn updateAccountInfoReturn = XMLBeanUtil.xml2Java(resultXmlString,UpdateAccountInfoReturn.class);
//            jsonObject = (JSONObject) JSON.toJSON(updateAccountInfoReturn);
            Document resultDocument = XMLStringUtil.string2Doc(resultXmlString);
            Element n_UpdateAccountInfo_1_0 = (Element) resultDocument
                    .getElementsByTagName("UpdateAccountInfo_1_0").item(0);
            if (n_UpdateAccountInfo_1_0 != null) {
                NodeList nodeList = n_UpdateAccountInfo_1_0.getChildNodes();
                if (nodeList != null && nodeList.getLength() > 0) {
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Node node = nodeList.item(i);
                        String nodeName = node.getNodeName();
                        String nodeValue = node.getTextContent();
                        jsonObject.put(nodeName, nodeValue);
                    }
                }
            }
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }
        return jsonObject;
    }

    /**
     * 单点登录
     *
     * @param judgeAccountByLoginID
     * @return
     */
    @Override
    public JSONObject ssoLogin(String tenant, String orgpk, JudgeAccountByLoginID judgeAccountByLoginID) {
        JSONObject jsonObject = null;
        if (StringUtils.isEmpty(judgeAccountByLoginID.getFunCode())) {
            judgeAccountByLoginID.setFunCode("MenuFL01");
        }
        //check the funCode
        logger.info("传入参数：");
        logger.info(supportedFunCode.getSupportedFunCodes().toString());
        if (!supportedFunCode.getSupportedFunCodes().contains(judgeAccountByLoginID.getFunCode())) {
            throw new BaseException(-100, "传入的跳转页面不正确");
        }
        try {
            String requestXmlString = XMLBeanUtil.java2Xml(judgeAccountByLoginID, "UTF-8");
            logger.info("请求XML字符串->");
            logger.info(requestXmlString);
            String resultXmlString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
            logger.info("返回XML字符串->");
            logger.info(resultXmlString);
            JudgeAccountByLoginIDReturn judgeAccountByLoginIDReturn = XMLBeanUtil.xml2Java(resultXmlString, JudgeAccountByLoginIDReturn.class);
            jsonObject = (JSONObject) JSON.toJSON(judgeAccountByLoginIDReturn);
        } catch (Exception e) {
            throw new BaseException(-100, e.getMessage());
        }
        return jsonObject;
    }

    /**
     * 自动审批接口
     *
     * @param checkApprove
     * @return
     */
    @Override
    public JSONObject autoApprove(String tenant, String orgpk, CheckApprove checkApprove) {
        //check the checkApprove
        if (StringUtils.isEmpty(checkApprove.getOrderNo()) || StringUtils.isEmpty(checkApprove.getProjectNo())
                || StringUtils.isEmpty(checkApprove.getIsDomc()) || StringUtils.isEmpty(checkApprove.getType())
                || StringUtils.isEmpty(checkApprove.getContactName())
                || StringUtils.isEmpty(checkApprove.getContantMobile())
                || StringUtils.isEmpty(checkApprove.getCreateUserCode())) {
            throw new BaseException(-100, "缺少参数信息");
        }
        JSONObject jsonObject = new JSONObject();
        String requestXmlString = "";
        try {
            requestXmlString = XMLBeanUtil.java2Xml(checkApprove, "UTF-8");
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }

        logger.info("请求XML字符串->");
        logger.info(requestXmlString);
        String resultXmlString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
        logger.info("返回XML字符串->");
        logger.info(resultXmlString);

        Document resultDocument = XMLStringUtil.string2Doc(resultXmlString);
        Element n_CheckApprove_1_0 = (Element) resultDocument
                .getElementsByTagName("CheckApprove_1_0").item(0);
        NodeList nodeList = n_CheckApprove_1_0.getChildNodes();
        if (nodeList != null && nodeList.getLength() > 0) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                String nodeName = node.getNodeName();
                String nodeValue = node.getTextContent();
                jsonObject.put(nodeName, nodeValue);
            }
        }
        return jsonObject;
    }

    /**
     * 机票订单列表抓取
     *
     * @param getFlightOrderList
     * @return
     */
    @Override
    public JSONObject getFlightOrderList(String tenant, String orgpk, GetFlightOrderList getFlightOrderList) {
        String requestXmlString = "";
        EntInfo entInfo = entInfoService.getEntInfoByTenantOrg(tenant, orgpk);
        try {
            requestXmlString = XMLBeanUtil.java2Xml(getFlightOrderList, "UTF-8");
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }

        logger.info("请求XML字符串->");
        logger.info(requestXmlString);
        String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
        logger.info("返回JSON字符串->");
        logger.info(resultJsonString);

        return processReturnString(resultJsonString);
    }

    /**
     * 获取机票订单详情
     *
     * @param getFlightOrderDetail
     * @return
     */
    @Override
    public JSONObject getFlightOrderDetail(String tenant, String orgpk, GetFlightOrderDetail getFlightOrderDetail) {
        String requestXmlString = "";
        try {
            requestXmlString = XMLBeanUtil.java2Xml(getFlightOrderDetail, "UTF-8");
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }
        logger.info("请求XML字符串->");
        logger.info(requestXmlString);
        String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
        logger.info("返回JSON字符串->");
        logger.info(resultJsonString);

        return processReturnString(resultJsonString);
    }

    @Override
    public JSONObject getTrainOrderList(String tenant, String orgpk, GetTrainOrderList getTrainOrderList) {
        String requestXmlString = "";
        try {
            requestXmlString = XMLBeanUtil.java2Xml(getTrainOrderList, "UTF-8");
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }

        logger.info("请求XML字符串->");
        logger.info(requestXmlString);
        String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
        logger.info("返回JSON字符串->");
        logger.info(resultJsonString);

        return processReturnString(resultJsonString);
    }

    /**
     * 获取火车票订单详情
     *
     * @param getTrainOrderDetail
     * @return
     */
    @Override
    public JSONObject getTrainOrderDetail(String tenant, String orgpk, GetTrainOrderDetail getTrainOrderDetail) {
        String requestXmlString = "";
        try {
            requestXmlString = XMLBeanUtil.java2Xml(getTrainOrderDetail, "UTF-8");
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }
        logger.info("请求XML字符串->");
        logger.info(requestXmlString);
        String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
        logger.info("返回JSON字符串->");
        logger.info(resultJsonString);

        return processReturnString(resultJsonString);
    }

    /**
     * 获取酒店订单列表
     *
     * @param getHotelOrderList
     * @return
     */
    @Override
    public JSONObject getHotelOrderList(String tenant, String orgpk, GetHotelOrderList getHotelOrderList) {
        String requestXmlString = "";
        try {
            requestXmlString = XMLBeanUtil.java2Xml(getHotelOrderList, "UTF-8");
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }

        logger.info("请求XML字符串->");
        logger.info(requestXmlString);
        String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
        logger.info("返回JSON字符串->");
        logger.info(resultJsonString);

        return processReturnString(resultJsonString);
    }

    /**
     * 获取酒店订单详情
     *
     * @param getHotelOrderDetail
     * @return
     */
    @Override
    public JSONObject getHotelOrderDetail(String tenant, String orgpk, GetHotelOrderDetail getHotelOrderDetail) {
        String requestXmlString = "";
        try {
            requestXmlString = XMLBeanUtil.java2Xml(getHotelOrderDetail, "UTF-8");
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }
        logger.info("请求XML字符串->");
        logger.info(requestXmlString);
        String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
        logger.info("返回JSON字符串->");
        logger.info(resultJsonString);

        return processReturnString(resultJsonString);
    }

    /**
     * 获取租车订单列表
     *
     * @param tenant          租户ID
     * @param orgpk           组织PK
     * @param getCarOrderList 条件
     * @return <code>JsonObject</code>
     */
    @Override
    public JSONObject getCarOrderList(String tenant, String orgpk, GetCarOrderList getCarOrderList) {
        String requestXmlString = "";
        try {
            requestXmlString = XMLBeanUtil.java2Xml(getCarOrderList, "UTF-8");
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }

        logger.info("请求XML字符串->");
        logger.info(requestXmlString);
        String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
        logger.info("返回JSON字符串->");
        logger.info(resultJsonString);

        return processReturnString(resultJsonString);
    }

    /**
     * 获取租车订单详情
     *
     * @param tenant            租户ID
     * @param orgpk             组织PK
     * @param getCarOrderDetail 条件
     * @return <code>JsonObject</code>
     */
    @Override
    public JSONObject getCarOrderDetail(String tenant, String orgpk, GetCarOrderDetail getCarOrderDetail) {
        String requestXmlString = "";
        try {
            requestXmlString = XMLBeanUtil.java2Xml(getCarOrderDetail, "UTF-8");
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }
        logger.info("请求XML字符串->");
        logger.info(requestXmlString);
        String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
        logger.info("返回JSON字符串->");
        logger.info(resultJsonString);

        return processReturnString(resultJsonString);
    }

    /**
     * 同步出差申请单
     *
     * @param tenant
     * @param orgpk
     * @param pushTravelApplyOrder
     * @return
     */
    @Override
    public JSONObject pushTravelApplyOrder(String tenant, String orgpk, PushTravelApplyOrder pushTravelApplyOrder) {
        String requestXmlString = "";
        JSONObject jsonObject = null;
        try {
            requestXmlString = XMLBeanUtil.java2Xml(pushTravelApplyOrder, "UTF-8");
            logger.info("请求XML字符串->");
            logger.info(requestXmlString);
            String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
            logger.info("返回JSON字符串->");
            logger.info(resultJsonString);

            PushTravelApplyOrderReturn pushTravelApplyOrderReturn = XMLBeanUtil.xml2Java(resultJsonString, PushTravelApplyOrderReturn.class);
            jsonObject = (JSONObject) JSON.toJSON(pushTravelApplyOrderReturn);
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }
        return jsonObject;
    }

    @Override
    public JSONObject getTravelCodeList(String tenant, String orgpk, GetTravelCodeList getTravelCodeList) {
        String requestXmlString = "";
        JSONObject jsonObject = null;
        try {
            requestXmlString = XMLBeanUtil.java2Xml(getTravelCodeList, "UTF-8");
            logger.info("请求XML字符串->");
            logger.info(requestXmlString);
            String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
            logger.info("返回JSON字符串->");
            logger.info(resultJsonString);

            GetTravelCodeListReturn getTravelCodeListReturn = XMLBeanUtil.xml2Java(resultJsonString, GetTravelCodeListReturn.class);
            jsonObject = (JSONObject) JSON.toJSON(getTravelCodeListReturn);
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }
        return jsonObject;
    }

    /**
     * 获取行政区划接口
     *
     * @param tenant
     * @param orgpk
     * @param getAdmdivCodeList
     * @return
     */
    @Override
    public JSONObject getAdmdivCodeList(String tenant, String orgpk, GetAdmdivCodeList getAdmdivCodeList) {
        String requestXmlString = "";
        JSONObject jsonObject = null;
        try {
            requestXmlString = XMLBeanUtil.java2Xml(getAdmdivCodeList, "UTF-8");
            logger.info("请求XML字符串->");
            logger.info(requestXmlString);
            String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
            logger.info("返回JSON字符串->");
            logger.info(resultJsonString);

            GetAdmdivCodeListReturn getAdmdivCodeListReturn = XMLBeanUtil.xml2Java(resultJsonString, GetAdmdivCodeListReturn.class);
            jsonObject = (JSONObject) JSON.toJSON(getAdmdivCodeListReturn);
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100, "实体类转XML错误");
        }
        return jsonObject;
    }

    /**
     * 处理一下中航的返回值
     * 成功为JSON格式
     * 失败为XML格式
     *
     * @param str
     * @return
     */
    private JSONObject processReturnString(String str) {
        JSONObject result = null;
        try {
            result = JSON.parseObject(str);
        } catch (Exception e) {
            //如果有异常，说明不是JSON格式，按照XML处理
            try {
                ErrorInfo errorInfo = XMLBeanUtil.xml2Java(str, ErrorInfo.class);
                result = (JSONObject) JSON.toJSON(errorInfo);
            } catch (JAXBException e1) {
                throw new BaseException(-100, "返回值转换XML格式异常");
            }
        }
        return result;
    }

    @Override
    public JSONObject pushApplayOrder(BriChannel channel,String tenant, String orgPk, JSONObject applyOrderJson) {
        JSONObject resultObject = new JSONObject();
        logger.info("中航易购申请单信息:" + applyOrderJson.toString());
        logger.info("开始拼装同步申请单数据");
        PushTravelApplyOrder data = processApplyDataV2(applyOrderJson,tenant, channel);
        logger.info("拼装同步申请单数据完成.开始推送");
        JSONObject resultJSON = null;
        String requestXmlString = "";
        try {
            requestXmlString = XMLBeanUtil.java2Xml(data,"UTF-8");
            logger.info("请求XML字符串->");
            logger.info(requestXmlString);
            String resultJsonString = cxfInvokeClient.callService(tenant,orgPk,requestXmlString,null);
            logger.info("返回JSON字符串->");
            logger.info(resultJsonString);

            PushTravelApplyOrderReturn pushTravelApplyOrderReturn = XMLBeanUtil.xml2Java(resultJsonString,PushTravelApplyOrderReturn.class);
            resultJSON = (JSONObject) JSON.toJSON(pushTravelApplyOrderReturn);
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100,"实体类转XML错误");
        }

        String applyOrderNo = resultJSON.getString("applyOrderNo");
        if (!StringUtils.isEmpty(applyOrderNo)){
            logger.info("中航易购同步成功，返回的外部申请单号=" + applyOrderNo);
            //返回true,ybz修改推送标记
            resultObject.put("msg","中航易购同步成功，返回的外部申请单号=" + applyOrderNo);
            resultObject.put("success",true);
        }
        else {
            String errorCode = resultJSON.getString("errorCode");
            //默认返回false
            resultObject.put("msg", resultJSON.getString("errorMsg"));
            resultObject.put("success", false);
            if (!StringUtils.isEmpty(errorCode) && errorCode.equals("6666")) {
                //同步成功的情况下，更新申请单的状态
                logger.info(resultJSON.getString("errorMsg"));
                if (resultJSON.getString("errorMsg").contains("该申请单已经存在，申请单号")) {
                    String outPk = resultJSON.getString("errorMsg").replace("该申请单已经存在，申请单号【", "").replace("】！", "");
                    if (!StringUtils.isEmpty(outPk)) {
                        //返回true,ybz修改推送标记
                        resultObject.put("msg", "该申请单已经存在，申请单号=" + outPk);
                        resultObject.put("success", true);
                    }
                }
            }
        }
        return resultObject;
    }

    /**
     * 设置超标审批人接口
     * @param param
     * @return
     */
    @Override
    public JSONObject exceedStandardApproval(JSONObject param) {
        String tenant = param.getString("tenantId");
        ExceedStandardApproval exceedStandardApproval = new ExceedStandardApproval();
        ExceedStandardApproval.ApproveAuditor approveAuditor = new ExceedStandardApproval.ApproveAuditor();
        List<ExceedStandardApproval.ApproveAuditor> approveAuditors = new ArrayList<>();
        List<ExceedStandardApproval.Traveler> travelers = new ArrayList<>();
        approveAuditor.setStaffNum(param.getString("pcode"));
        approveAuditor.setApprovePriority("1");
        String orgpk = param.getString("orgpk");
        approveAuditors.add(approveAuditor);
        JSONArray users = param.getJSONArray("users");
        if (!CollectionUtils.isEmpty(users)) {
            for (Object user : users) {
                JSONObject userJson = JSONObject.parseObject(JSON.toJSONString(user));
                ExceedStandardApproval.Traveler traveler = new ExceedStandardApproval.Traveler();
                traveler.setStaffNum(userJson.getString("pcode"));
                travelers.add(traveler);
            }
        }
        JSONArray pcodes = param.getJSONArray("pcodes");
        JSONArray userIds = param.getJSONArray("userIds");

        // 在设置二次授权人之前，先同步相关用户到中航易购
        List<String> userIdsNotSync = new CopyOnWriteArrayList<>();
        List<String> userIdList = userIds.toJavaList(String.class);
        userIdList.add(param.getString("userid"));
        if (!CollectionUtils.isEmpty(userIdList)) {
            for (String userId : userIdList) {
                List<RtpnrUser> rtpnrUsers = rtpnrUserService.selectList(new EntityWrapper<RtpnrUser>().where("tenant={0}", tenant).and("user_id={0}", userId));
                if (CollectionUtils.isEmpty(rtpnrUsers)) {
                    userIdsNotSync.add(userId);
                }
            }
        }
        if (!CollectionUtils.isEmpty(userIdsNotSync)) {
            List<UcUserDto> completeUcUserByUserIds = iUserCenterService.getCompleteUcUserDtoByUserid(userIdsNotSync, tenant);
            if (!CollectionUtils.isEmpty(completeUcUserByUserIds)) {
                rtpnrUserService.syncUsersByUserCenterListener(tenant, orgpk, completeUcUserByUserIds);
            }
        }
        // end 人员同步

        if (!CollectionUtils.isEmpty(pcodes)) {
            for (Object pcodeObject : pcodes) {
                ExceedStandardApproval.Traveler traveler = new ExceedStandardApproval.Traveler();
                traveler.setStaffNum(String.valueOf(pcodeObject));
                travelers.add(traveler);
            }
        }
        exceedStandardApproval.setApproveAuditors(approveAuditors.toArray(new ExceedStandardApproval.ApproveAuditor[0]));
        exceedStandardApproval.setTravelers(travelers.toArray(new ExceedStandardApproval.Traveler[0]));
        JSONObject resultJSON = null;
        String requestXmlString = "";
        try {
            requestXmlString = XMLBeanUtil.java2Xml(exceedStandardApproval, "UTF-8");
            logger.info("请求XML字符串->");
            logger.info(requestXmlString);
            String resultJsonString = cxfInvokeClient.callService(tenant, orgpk, requestXmlString, null);
            logger.info("返回JSON字符串->");
            logger.info(resultJsonString);
            ExceedStandardApprovalReturn exceedStandardApprovalReturn = XMLBeanUtil.xml2Java(resultJsonString, ExceedStandardApprovalReturn.class);
            resultJSON = (JSONObject) JSON.toJSON(exceedStandardApprovalReturn);
        } catch (JAXBException e) {
            logger.error(e.getMessage());
            throw new BaseException(-100,"实体类转XML错误");
        }
        return resultJSON;
    }

    private PushTravelApplyOrder processApplyData(JSONObject applyOrderJson, String tenant) {
        JSONObject nodeBusinessTrip = applyOrderJson;
        JSONObject special = nodeBusinessTrip.getJSONObject("special");
        String userId = nodeBusinessTrip.getString("userId");
        //把json转化成PushTravelApplyOrder
        PushTravelApplyOrder pushTravelApplyOrder = new PushTravelApplyOrder();
        pushTravelApplyOrder.setOutOrderNo(special.getString("applayNumber"));
        Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (nodeBusinessTrip.getDate("startDate") != null) {
            pushTravelApplyOrder.setStartDate(f.format(nodeBusinessTrip.getDate("startDate")));
        }
        if (nodeBusinessTrip.getDate("endDate") != null) {
            pushTravelApplyOrder.setEndDate(f.format(nodeBusinessTrip.getDate("endDate")));
        }

        pushTravelApplyOrder.setRemark(applyOrderJson.getString("Remark"));
        pushTravelApplyOrder.setCreateAccount(applyOrderJson.getString("CreateAccount"));
        pushTravelApplyOrder.setTravelCode(special.getString("TravelCode"));
//        pushTravelApplyOrder.setLocationCode(applyOrderJson.getString("LocationCode"));
//        pushTravelApplyOrder.setLocationName(applyOrderJson.getString("LocationName"));
        pushTravelApplyOrder.setMatters(nodeBusinessTrip.getString("descript"));
        pushTravelApplyOrder.setApproveType("0");
        pushTravelApplyOrder.setIsValidateTrip("N");
        pushTravelApplyOrder.setIsRental(special.getString("IsRental"));

        // 单据详情
        JSONArray travelList = nodeBusinessTrip.getJSONArray("nodeBusinessTravelList");
        Set<String> trafficCodeSet = new HashSet<>();
        List<PushTravelApplyOrder.FlightTrip> flightTripList = new ArrayList<>();
        List<PushTravelApplyOrder.TrainTrip> trainTripList = new ArrayList<>();
        List<PushTravelApplyOrder.HotelTrip> hotelTripList = new ArrayList<>();
        if (travelList != null && travelList.size() > 0) {
            for (int i = 0; i < travelList.size(); i++) {
                JSONObject travel = travelList.getJSONObject(i);
                String tripWay = travel.getString("tripWay");
                String tripType = travel.getString("tripType");
                if ("飞机".equals(tripWay)) {
                    trafficCodeSet.add("JP");
                    PushTravelApplyOrder.FlightTrip flightTrip = new PushTravelApplyOrder.FlightTrip();
//                    flightTrip.setFlightWay(tripType);
                    flightTrip.setDepartDate("");
                    flightTrip.setDepartDateBegin("");
                    flightTrip.setDepartDateEnd("");
                    flightTrip.setIsDomc(judgeIsDomc(nodeBusinessTrip, tenant));
                    flightTrip.setReturnDate("");
                    flightTrip.setReturnDateBegin("");
                    flightTrip.setReturnDateEnd("");
                    flightTrip.setFromCityCode("");
                    flightTrip.setToCityCode("");
                    flightTripList.add(flightTrip);
                } else if ("火车".equals(tripWay)) {
                    trafficCodeSet.add("HC");
                    PushTravelApplyOrder.TrainTrip trainTrip = new PushTravelApplyOrder.TrainTrip();
//                    trainTrip.setTripType(tripType);
                    trainTrip.setDepartDate("");
                    trainTrip.setDepartDateBegin("");
                    trainTrip.setDepartDateEnd("");
                    trainTrip.setIsDomc(judgeIsDomc(nodeBusinessTrip, tenant));
                    trainTrip.setReturnDate("");
                    trainTrip.setReturnDateBegin("");
                    trainTrip.setReturnDateEnd("");
                    trainTrip.setFromCityName("");
                    trainTrip.setToCityName("");
                    trainTripList.add(trainTrip);
                }
            }
        } else {
            //没有行程明细时，做一条只有IsDomc的明细
            //机票
            PushTravelApplyOrder.FlightTrip flightTrip = new PushTravelApplyOrder.FlightTrip();
            flightTrip.setIsDomc(judgeIsDomc(nodeBusinessTrip, tenant));
            flightTripList.add(flightTrip);
            //火车
            PushTravelApplyOrder.TrainTrip trainTrip = new PushTravelApplyOrder.TrainTrip();
            trainTrip.setIsDomc(judgeIsDomc(nodeBusinessTrip, tenant));
            trainTripList.add(trainTrip);
        }
        //酒店

        PushTravelApplyOrder.HotelTrip hotelTrip = new PushTravelApplyOrder.HotelTrip();
        hotelTrip.setIsDomc(judgeIsDomc(nodeBusinessTrip, tenant));
        hotelTripList.add(hotelTrip);

        StringBuffer trafficCodeBuffer = new StringBuffer();
        if (trafficCodeSet.size() > 0) {
            String[] strings = trafficCodeSet.toArray(new String[0]);
            for (int i = 0; i < strings.length; i++) {
                if (i != strings.length - 1) {
                    trafficCodeBuffer.append(strings[i]).append(",");
                } else {
                    trafficCodeBuffer.append(strings[i]);
                }
            }
        }

        //收集userID
        Set<String> userSet = new HashSet<>();
        userSet.add(userId);
        userSet.add(userId);
        Map<String, String> userId2Pcode = new HashMap<>();
        //根据userID查pcode
        List<UcUserDto> completeUcUserDtoByUserid = iUserCenterService.getCompleteUcUserDtoByUserid(Arrays.asList(userSet.toArray(new String[0])), tenant);
        if (completeUcUserDtoByUserid != null && completeUcUserDtoByUserid.size() > 0) {
            completeUcUserDtoByUserid.forEach(userDto -> {
                userId2Pcode.put(userDto.getUserId(), userDto.getPersonCode());
            });
        }
        logger.info("------------友报账传过来的申请人员工编号为" + userId);
        logger.info("------------通过userId查pCode为" + userId2Pcode.get(userId));
        //设置pcode
        if (StringUtils.isEmpty(userId2Pcode.get(userId))) {
            Wrapper<RtpnrUser> rtpnrUserWrapper = new EntityWrapper<>();
            rtpnrUserWrapper.where("user_id={0}", userId);
            List<RtpnrUser> rtpnrUsers = rtpnrUserService.selectList(rtpnrUserWrapper);
            if (rtpnrUsers != null && rtpnrUsers.size() > 0) {
                userId2Pcode.put(userId, rtpnrUsers.get(0).getStaffNum());
            }

        }
        pushTravelApplyOrder.setCreateStaffNum(userId2Pcode.get(userId));
        //出差人信息

        List<PushTravelApplyOrder.Traveler> travelerList = new ArrayList<>();
        PushTravelApplyOrder.Traveler traveler = new PushTravelApplyOrder.Traveler();
        traveler.setStaffNum(userId2Pcode.get(userId));
        if (trafficCodeBuffer != null && trafficCodeBuffer.length() > 0) {
            traveler.setTrafficCode(trafficCodeBuffer.toString());
        } else {
            traveler.setTrafficCode("JP,HC,QC,QT");
        }
        travelerList.add(traveler);


        pushTravelApplyOrder.setTravelers(travelerList.toArray(new PushTravelApplyOrder.Traveler[0]));
        pushTravelApplyOrder.setFlightTrips(flightTripList.toArray(new PushTravelApplyOrder.FlightTrip[0]));
        pushTravelApplyOrder.setTrainTrips(trainTripList.toArray(new PushTravelApplyOrder.TrainTrip[0]));
        pushTravelApplyOrder.setHotelTrips(hotelTripList.toArray(new PushTravelApplyOrder.HotelTrip[0]));

        return pushTravelApplyOrder;
    }

    private PushTravelApplyOrder processApplyDataV2(JSONObject applyOrderJson, String tenant, BriChannel channel) {
        JSONObject nodeBusinessTrip = applyOrderJson;
        JSONObject special = nodeBusinessTrip.getJSONObject("special");
        String userId = nodeBusinessTrip.getString("userId");
        //把json转化成PushTravelApplyOrder
        PushTravelApplyOrder pushTravelApplyOrder = new PushTravelApplyOrder();
        pushTravelApplyOrder.setOutOrderNo(special.getString("applayNumber"));
        Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (nodeBusinessTrip.getDate("startDate") != null) {
            pushTravelApplyOrder.setStartDate(f.format(nodeBusinessTrip.getDate("startDate")));
        }
        if (nodeBusinessTrip.getDate("endDate") != null) {
            pushTravelApplyOrder.setEndDate(f.format(nodeBusinessTrip.getDate("endDate")));
        }

        String osType = special.getString("openType");

        pushTravelApplyOrder.setRemark(applyOrderJson.getString("Remark"));
        //同步费用归属信息
        //例：1EAF75F6-2C43-4E1F-9221-DE24D8926895,财务部1(旧数据，新数据没有名称)
        processCostInfo(tenant, userId, osType, pushTravelApplyOrder, channel, applyOrderJson);

        pushTravelApplyOrder.setCreateAccount(applyOrderJson.getString("CreateAccount"));
        pushTravelApplyOrder.setTravelCode(special.getString("TravelCode"));
//        pushTravelApplyOrder.setLocationCode(applyOrderJson.getString("LocationCode"));
//        pushTravelApplyOrder.setLocationName(applyOrderJson.getString("LocationName"));
        pushTravelApplyOrder.setMatters(nodeBusinessTrip.getString("descript"));
        pushTravelApplyOrder.setApproveType("0");
        pushTravelApplyOrder.setIsValidateTrip("N");
        pushTravelApplyOrder.setIsRental(special.getString("IsRental"));

        // 单据详情
        JSONArray travelList = nodeBusinessTrip.getJSONArray("nodeBusinessTravelList");
        Set<String> trafficCodeSet = new HashSet<>();
        List<PushTravelApplyOrder.FlightTrip> flightTripList = new ArrayList<>();
        List<PushTravelApplyOrder.TrainTrip> trainTripList = new ArrayList<>();
        List<PushTravelApplyOrder.HotelTrip> hotelTripList = new ArrayList<>();
        if (travelList != null && travelList.size() > 0) {
            for (int i = 0; i < travelList.size(); i++) {
                JSONObject travel = travelList.getJSONObject(i);
                String tripWay = travel.getString("tripWay");
                String tripType = travel.getString("tripType");
                JSONObject cityCodeMap = special.getJSONObject("cityCodes");
                String fromCode = cityCodeMap.getString(travel.getString("fromCity"));
                String toCode = cityCodeMap.getString(travel.getString("toCity"));
                if ("飞机".equals(tripWay)) {
                    trafficCodeSet.add("JP");
                    PushTravelApplyOrder.FlightTrip flightTrip = new PushTravelApplyOrder.FlightTrip();
//                    flightTrip.setFlightWay(tripType);
                    flightTrip.setDepartDate("");
                    flightTrip.setDepartDateBegin("");
                    flightTrip.setDepartDateEnd("");
                    flightTrip.setIsDomc(judgeIsDomc(nodeBusinessTrip, tenant));
                    flightTrip.setReturnDate("");
                    flightTrip.setReturnDateBegin("");
                    flightTrip.setReturnDateEnd("");
                    flightTrip.setFromCityCode(fromCode);
                    flightTrip.setToCityCode(toCode);
                    flightTripList.add(flightTrip);
                } else if ("火车".equals(tripWay)) {
                    trafficCodeSet.add("HC");
                    PushTravelApplyOrder.TrainTrip trainTrip = new PushTravelApplyOrder.TrainTrip();
//                    trainTrip.setTripType(tripType);
                    trainTrip.setDepartDate("");
                    trainTrip.setDepartDateBegin("");
                    trainTrip.setDepartDateEnd("");
                    trainTrip.setIsDomc(judgeIsDomc(nodeBusinessTrip, tenant));
                    trainTrip.setReturnDate("");
                    trainTrip.setReturnDateBegin("");
                    trainTrip.setReturnDateEnd("");
                    trainTrip.setFromCityName(travel.getString("fromCity"));
                    trainTrip.setToCityName(travel.getString("toCity"));
                    trainTripList.add(trainTrip);
                }
            }
        } else {
            //没有行程明细时，做一条只有IsDomc的明细
            //机票
            PushTravelApplyOrder.FlightTrip flightTrip = new PushTravelApplyOrder.FlightTrip();
            flightTrip.setIsDomc(judgeIsDomc(nodeBusinessTrip, tenant));
            flightTripList.add(flightTrip);
            //火车
            PushTravelApplyOrder.TrainTrip trainTrip = new PushTravelApplyOrder.TrainTrip();
            trainTrip.setIsDomc(judgeIsDomc(nodeBusinessTrip, tenant));
            trainTripList.add(trainTrip);
        }
        //酒店

        PushTravelApplyOrder.HotelTrip hotelTrip = new PushTravelApplyOrder.HotelTrip();
        hotelTrip.setIsDomc(judgeIsDomc(nodeBusinessTrip, tenant));

        JSONObject hotelCity = applyOrderJson.getJSONObject("hotelCities");
        if (hotelCity != null){
            ArrayList<String> toCitesList = new ArrayList<>(hotelCity.keySet());
            ArrayList<String> toCitesCodeList = new ArrayList(hotelCity.values());
            hotelTrip.setToCityName(String.join(",",toCitesList));
            hotelTrip.setToCityCode(String.join(",",toCitesCodeList));
        }
        hotelTripList.add(hotelTrip);

        StringBuffer trafficCodeBuffer = new StringBuffer();
        if (trafficCodeSet.size() > 0) {
            String[] strings = trafficCodeSet.toArray(new String[0]);
            for (int i = 0; i < strings.length; i++) {
                if (i != strings.length - 1) {
                    trafficCodeBuffer.append(strings[i]).append(",");
                } else {
                    trafficCodeBuffer.append(strings[i]);
                }
            }
        }

        //收集userID
        Set<String> userSet = new HashSet<>();
        userSet.add(userId);
        userSet.add(userId);
        Map<String, String> userId2Pcode = new HashMap<>();
        //根据userID查pcode
        List<UcUserDto> completeUcUserDtoByUserid = iUserCenterService.getCompleteUcUserDtoByUserid(Arrays.asList(userSet.toArray(new String[0])), tenant);
        if (completeUcUserDtoByUserid != null && completeUcUserDtoByUserid.size() > 0) {
            completeUcUserDtoByUserid.forEach(userDto -> {
                userId2Pcode.put(userDto.getUserId(), userDto.getPersonCode());

                List<UcUserDto> list = new ArrayList<>();
                list.add(userDto);
                try {
                    Wrapper<RtpnrUser> wrapper = new EntityWrapper<>();
                    wrapper.eq(RtpnrUser.TENANT, tenant);
                    wrapper.eq(RtpnrUser.ORGPK, userDto.getOrgPk());
                    wrapper.eq(RtpnrUser.USER_ID, userDto.getUserId());
                    List<RtpnrUser> rtpnrUsers = rtpnrUserService.selectList(wrapper);
                    if (CollectionUtils.isEmpty(rtpnrUsers)){
                        rtpnrUserService.syncUsersByUserCenterListener(tenant, userDto.getOrgPk(), list);
                    }
                }catch (Exception e){
                    logger.error("同步中航易购申请单同步制单人员异常：" + e.getMessage());
                    e.printStackTrace();
                }
            });
        }
        logger.info("------------友报账传过来的申请人员工编号为" + userId);
        logger.info("------------通过userId查pCode为" + userId2Pcode.get(userId));
        //设置pcode
        if (StringUtils.isEmpty(userId2Pcode.get(userId))) {
            Wrapper<RtpnrUser> rtpnrUserWrapper = new EntityWrapper<>();
            rtpnrUserWrapper.where("user_id={0}", userId);
            List<RtpnrUser> rtpnrUsers = rtpnrUserService.selectList(rtpnrUserWrapper);
            if (rtpnrUsers != null && rtpnrUsers.size() > 0) {
                userId2Pcode.put(userId, rtpnrUsers.get(0).getStaffNum());
            }

        }
        pushTravelApplyOrder.setCreateStaffNum(userId2Pcode.get(userId));
        //出差人信息

        List<PushTravelApplyOrder.Traveler> travelerList = new ArrayList<>();


        //实际出行人
        List<String> companionList = new ArrayList<>();
        boolean success = getPassenger(channel, companionList, nodeBusinessTrip, tenant,completeUcUserDtoByUserid.get(0), osType);
        if (success) {
            for (String pcode : companionList) {
                PushTravelApplyOrder.Traveler traveler = new PushTravelApplyOrder.Traveler();

                traveler.setStaffNum(pcode);
                if (trafficCodeBuffer != null && trafficCodeBuffer.length() > 0) {
                    traveler.setTrafficCode(trafficCodeBuffer.toString());
                } else {
                    traveler.setTrafficCode("JP,HC,QC,QT");
                }
                travelerList.add(traveler);
            }
        }else {
            PushTravelApplyOrder.Traveler traveler = new PushTravelApplyOrder.Traveler();

            traveler.setStaffNum(userId2Pcode.get(userId));
            if (trafficCodeBuffer != null && trafficCodeBuffer.length() > 0) {
                traveler.setTrafficCode(trafficCodeBuffer.toString());
            } else {
                traveler.setTrafficCode("JP,HC,QC,QT");
            }
            travelerList.add(traveler);
        }




        pushTravelApplyOrder.setTravelers(travelerList.toArray(new PushTravelApplyOrder.Traveler[0]));
        pushTravelApplyOrder.setFlightTrips(flightTripList.toArray(new PushTravelApplyOrder.FlightTrip[0]));
        pushTravelApplyOrder.setTrainTrips(trainTripList.toArray(new PushTravelApplyOrder.TrainTrip[0]));
        pushTravelApplyOrder.setHotelTrips(hotelTripList.toArray(new PushTravelApplyOrder.HotelTrip[0]));

        return pushTravelApplyOrder;
    }

    /**
     * 同步费用归属信息
     * @param pushTravelApplyOrder
     * @param channel
     * @param applyOrderJson
     */
    private void processCostInfo(String tenant, String userId, String osType, PushTravelApplyOrder pushTravelApplyOrder, BriChannel channel, JSONObject applyOrderJson) {
        if (channel != null && channel.getSyncCostInfo() != 0){
            String assumeDept = applyOrderJson.getString("assumeDept");
            String assumeOrg = applyOrderJson.getString("assumeOrg");
            String costProject = applyOrderJson.getString("costProject");
            String[] assumeDeptArr = assumeDept!= null ? assumeDept.split(",") : null;
            String[] assumeOrgArr = assumeOrg!= null ? assumeOrg.split(",") : null;
            String[] costProjectArr = costProject!= null ? costProject.split(",") : null;
            switch (channel.getSyncCostInfo()){
                //传名称
                case 1:
                    if (assumeDeptArr != null && assumeDeptArr.length > 0){
                        //费用承担部门——costbearingdepcode
                        if (assumeDeptArr.length > 1){
                            pushTravelApplyOrder.setCostBearingDepName(assumeDeptArr[1]);

                        }else {
                            String assumeDeptPk = assumeDeptArr[0];
                            Map<String, String> deptInfo = baseDocService.getDeptByOsType(tenant, userId ,assumeDeptPk, osType);
                            String assumeDeptName =  deptInfo != null ? deptInfo.get("name") : "";
                            pushTravelApplyOrder.setCostBearingDepName(assumeDeptName);
                        }

                    }
                    if (assumeOrgArr != null && assumeOrgArr.length > 0){
                        //费用承担单位——remark
                        if (assumeOrgArr.length > 1){
                            pushTravelApplyOrder.setCostBearingOrgCodeName(assumeOrgArr[1]);

                        }else {
                            String assumeOrgPk = assumeOrgArr[0];
                            Map<String, String> orgInfo = baseDocService.getOrgByOsType(tenant, userId, assumeOrgPk, osType);
                            String assumeOrgName = orgInfo != null ? orgInfo.get("name") : "";

                            pushTravelApplyOrder.setCostBearingOrgCodeName(assumeOrgName);
                        }

                    }
                    if (costProjectArr != null && costProjectArr.length > 0){
                        if (costProjectArr.length > 1){
                            pushTravelApplyOrder.setProjectNo(costProjectArr[1]);

                        }else {
                            String costProjectPk = costProjectArr[0];
                            Map<String, String> projectInfo = baseDocService.getInOutProjectByOsType(tenant, userId, costProjectPk, osType);
                            String costProjectName = projectInfo != null ? projectInfo.get("name") : "";
                            pushTravelApplyOrder.setProjectNo(costProjectName);
                        }

                    }
                    break;
                //传pk
                case 2:
                    if (assumeDeptArr != null && assumeDeptArr.length > 0){
                        //费用承担部门——costbearingdepcode
                        pushTravelApplyOrder.setCostBearingDepCode(assumeDeptArr[0]);
                    }
                    if (assumeOrgArr != null && assumeOrgArr.length > 0){
                        //费用承担单位——remark
                        pushTravelApplyOrder.setCostBearingOrgCode(assumeOrgArr[0]);
                    }
                    if (costProjectArr != null && costProjectArr.length > 0){
                        pushTravelApplyOrder.setProjectNo(costProjectArr[0]);
                    }
                    break;
                default:
                    if (assumeDeptArr != null && assumeDeptArr.length > 0){
                        //费用承担部门——costbearingdepcode
                        pushTravelApplyOrder.setCostBearingDepCode(assumeDeptArr[0]);
                    }
                    if (assumeOrgArr != null && assumeOrgArr.length > 0){
                        //费用承担单位——remark
                        pushTravelApplyOrder.setCostBearingOrgCode(assumeOrgArr[0]);
                    }
                    if (costProjectArr != null && costProjectArr.length > 0){
                        pushTravelApplyOrder.setProjectNo(costProjectArr[0]);
                    }
                    if (assumeDeptArr != null && assumeDeptArr.length > 1){
                        //费用承担部门——costbearingdepcode
                        pushTravelApplyOrder.setCostBearingDepName(assumeDeptArr[1]);
                    }
                    if (assumeOrgArr != null && assumeOrgArr.length > 1){
                        //费用承担单位——remark
                        pushTravelApplyOrder.setCostBearingOrgCodeName(assumeOrgArr[1]);
                    }
                    if (costProjectArr != null && costProjectArr.length > 1){
                        pushTravelApplyOrder.setProjectNo(costProjectArr[1]);
                    }

                    break;
            }
        }
    }

    private boolean getPassenger(BriChannel briChannel, List<String> companionList, JSONObject nodeBusinessTrip, String tenant, UcUserDto sscUser, String opentType){
        // 报账3.18新增市级出行人字段格式为{pk;pk}
        String actualPedestrian = nodeBusinessTrip.getString("actualPedestrian");

        // 旧的实际出行人为手输格式，支持格式  张三（17934125896），李四（14536897562）
        String companion = nodeBusinessTrip.getString("companion");

        if (org.apache.commons.lang3.StringUtils.isNotBlank(actualPedestrian)){
            actualPedestrian = convertTraveler(actualPedestrian);
            String[] split = actualPedestrian.split(";");
            List<String> personIds = new ArrayList<>();
            for (String str : split) {
                if (str.split(",").length>0){
                    personIds.add(str.split(",")[0]);
                }
            }
            List<UcUserDto> companionUser = null;
            if ("nc".equals(opentType)){
                companionUser = iUserCenterService.getCompleteUcUserByPersonIds(personIds,tenant);
            }else {
                companionUser = iUserCenterService.getCompleteUcUserDtoByUserid(personIds,tenant);
            }

            if (companionUser != null && companionUser.size() == personIds.size()){
                for (UcUserDto ucUserDto : companionUser) {
                    if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                        List<UcUserDto> list = new ArrayList<>();
                        list.add(ucUserDto);
                        try {
                            Wrapper<RtpnrUser> wrapper = new EntityWrapper<>();
                            wrapper.eq(RtpnrUser.TENANT, tenant);
                            wrapper.eq(RtpnrUser.ORGPK, ucUserDto.getOrgPk());
                            wrapper.eq(RtpnrUser.USER_ID, ucUserDto.getUserId());
                            List<RtpnrUser> rtpnrUsers = rtpnrUserService.selectList(wrapper);
                            if (CollectionUtils.isEmpty(rtpnrUsers)){
                                rtpnrUserService.syncUsersByUserCenterListener(tenant, ucUserDto.getOrgPk(), list);
                            }
                        }catch (Exception e){
                            logger.error("同步中航易购申请单同步人员异常：" + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                    companionList.add(ucUserDto.getPersonCode());
                }
            }else {
                logger.info("用户中心未找到实际出行人:" + personIds.toString());
                throw new BusinessException("用户中心未找到部分实际出行人");
            }
        }
        //中航易购需要传personcode，所以companion里必须包含手机号才生效 例如：张三(1555555555)
        if (org.apache.commons.lang3.StringUtils.isNotBlank(companion)) {
            companion = convertTraveler(companion);
            if (!org.apache.commons.lang3.StringUtils.isEmpty(companion) && companion.contains(":")) {
                String[] split = companion.split(",");
                for (String str : split) {
                    String[] strings = str.split(":");
                    if (strings.length > 1){
                        //如果手输实际出行人和制单人一致，则忽略
                        if (split.length == 1 && strings[0].equals(sscUser.getUserName())){
                            continue;
                        }
                        String phoneNo = strings[1];
                        UcUserDto companionUser = iUserCenterService.getCompleteUcUserDtoByPhone(phoneNo, tenant);
                        if (companionUser != null && org.apache.commons.lang3.StringUtils.isNotEmpty(companionUser.getPersonCode())) {
                            if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                                List<UcUserDto> list = new ArrayList<>();
                                list.add(companionUser);
                                try {
                                    Wrapper<RtpnrUser> wrapper = new EntityWrapper<>();
                                    wrapper.eq(RtpnrUser.TENANT, tenant);
                                    wrapper.eq(RtpnrUser.ORGPK, companionUser.getOrgPk());
                                    wrapper.eq(RtpnrUser.USER_ID, companionUser.getUserId());
                                    List<RtpnrUser> rtpnrUsers = rtpnrUserService.selectList(wrapper);
                                    if (CollectionUtils.isEmpty(rtpnrUsers)){
                                        rtpnrUserService.syncUsersByUserCenterListener(tenant, companionUser.getOrgPk(), list);
                                    }
                                }catch (Exception e){
                                    logger.error("同步中航易购申请单同步人员异常：" + e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                            companionList.add(companionUser.getPersonCode());
                        } else {
                            String msg = "用户中心未找到或部分未找到实际出行人companion:" + phoneNo;
                            logger.info(msg);
                            return false;
                        }
                    }else {
                        logger.error("中航易购未填写手机号：" + str);
                    }
                }
            }
        }

        if(CollectionUtils.isEmpty(companionList)) {
            companionList.add(sscUser.getPersonCode());
        }
        return true;
    }

    /**
     * 转换companion中的字符
     *
     * @param companion
     * @return
     */
    public static String convertTraveler(String companion) {
        String convertStr = companion;
        if (companion.contains("（")) {
            convertStr = companion.replaceAll("（", ":");
        }
        if (companion.contains("(")) {
            convertStr = convertStr.replaceAll("\\(", ":");
        }
        if (companion.contains("）")) {
            convertStr = convertStr.replaceAll("）", "");
        }
        if (companion.contains(")")) {
            convertStr = convertStr.replaceAll("\\)", "");
        }
        if (companion.contains("，")) {
            convertStr = convertStr.replaceAll("，", ",");
        }
        if (companion.contains("、")) {
            convertStr = convertStr.replaceAll("、", ",");
        }
        return convertStr;
    }


    private String judgeIsDomc(JSONObject nodeBusinessTrip, String tenant) {
        String defitem4 = nodeBusinessTrip.getString("defitem4");
        if ("a7exr9xj".equals(tenant) && defitem4 != null) {
            if (defitem4.contains(",")) {
                String[] split = defitem4.split(",");
                if ("f9b7f97bf33a4f4c860aa721da6776a2".equals(split[0]) || "c1219dd004a64bef9cdfdc33819fc017".equals(split[0])) {
                    return "D";
                } else if ("04ce0c4493664321909c756213d4febf".equals(split[0])) {
                    return "I";
                }
            } else if ("f9b7f97bf33a4f4c860aa721da6776a2".equals(defitem4) || "c1219dd004a64bef9cdfdc33819fc017".equals(defitem4)) {
                return "D";
            } else if ("04ce0c4493664321909c756213d4febf".equals(defitem4)) {
                return "I";
            }
        }
        return "D";
    }
}
